package com.jkt.rms.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.jkt.rms.business.Users;
import com.jkt.rms.businessservice.UserBusinessService;
import com.jkt.rms.commons.configuration.MessageSourceImpl;
import com.jkt.rms.commons.utils.ExceptionFactory;
import com.jkt.rms.commons.utils.RMSException;
import com.jkt.rms.commons.utils.ServiceLocator;
import com.jkt.rms.vo.UsersVO;

/**
 * This class provides functionality of Forgot password.
 * 
 * @author JKT
 * @version 0.1
 */

public class ForgotPasswordController extends SimpleFormController {

	private static final String USER_MODEL = "user";

	private static final String FORGOT_PASSWORD_UI = "forgotpassword";

	private static final String FAILURE_MESSAGE = "Application error occurs";

	private static final Logger LOG = Logger
			.getLogger(ForgotPasswordController.class);

	private UserBusinessService userBusinessService;
	
	private MessageSourceImpl messagesourceimpl;
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws RMSException {
		LOG.debug(this.getClass().getSimpleName());
		UsersVO userData = (UsersVO) command;
		userBusinessService = ServiceLocator.getServiceLocator().locate(
				"userBusinessService");
		messagesourceimpl = ServiceLocator.getServiceLocator().locate("messageSourceImpl");
			try {
				Users user = userBusinessService.getUserData(userData);
				if (user == null) {
					errors.reject("pwd.failure.message");
				} else {
					userBusinessService.pwdEmailService(user);
					userData.setMessage(messagesourceimpl.getMessage("pwd.success.message"));
					userData.setUsername("");
				}

			} catch (RMSException e) {
				LOG.error("Exception Occurs :" + e.getCause());
				errors.reject(e.getBusinessCode());
			} catch (Exception ex) {
				ExceptionFactory.createRMSException(LOG, ex.getCause(), FAILURE_MESSAGE);
				errors.reject("error.application");
			}
			finally{
//				TODO: complete definition.
			}
		return new ModelAndView(FORGOT_PASSWORD_UI, USER_MODEL, userData).addObject("errors",errors);
		
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws RMSException {
		UsersVO user = new UsersVO();
		return user;
	}
}
